import moment from 'moment';

;(() => {
  const oList = document.querySelector('#list');
  const oMsg = document.querySelector('#message');
  const oSendBtn = document.querySelector('#send');

  const ws = new WebSocket('ws://localhost:5211');

  let username = ''

  const init = () => {
    bindEvent();
  }

  function bindEvent () {
    oSendBtn.addEventListener('click', handleSendBtnClcik, false);
    ws.addEventListener('open', handleOpen, false);
    ws.addEventListener('close', handleClose, false);
    ws.addEventListener('error', handleError, false);
    ws.addEventListener('message', handleMessage, false);
  }

  function handleSendBtnClcik () {
    const message = oMsg.value;

    //除了空格用户没有内容输入
    if (message.trim().length === 0) {
      return;
    }

    ws.send(JSON.stringify({
      user: username,
      time: new Date().getTime(),
      message
    }))

    oMsg.value = '';
  }

  function handleOpen () {
    const name = localStorage.getItem('user_name');

    if (!name || name.trim().length === 0) {
      location.href = 'entry.html';
    }

    username = name;
  }

  function handleClose () {

  }

  function handleError () {

  }

  function handleMessage (e) {
    const msgData = JSON.parse(e.data);
    oList.appendChild(createMsgItem(msgData));
  }

  function createMsgItem (data) {
    const {username, time, message} = data;
    const oItem = document.createElement('li');
    oItem.innerHTML = `
      <p>
        <span>${username}</span>
        <i>${moment(time).format('YYYY-MM-DD HH:mm:ss')}</i>
      </p>
      <p>消息：${message}</p>
    `
    return oItem;
  }

  init();
})();